/**
 * 
 */
package com.netflexitysolutions.amazonws.sdb.internal.operations;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.amazonaws.sdb.doc._2009_04_15.Attribute;
import com.amazonaws.sdb.doc._2009_04_15.GetAttributes;
import com.amazonaws.sdb.doc._2009_04_15.GetAttributesResponse;
import com.amazonaws.sdb.doc._2009_04_15.GetAttributesResult;
import com.amazonaws.sdb.doc._2009_04_15.ResponseMetadata;
import com.netflexitysolutions.amazonws.sdb.Domain;
import com.netflexitysolutions.amazonws.sdb.Item;
import com.netflexitysolutions.amazonws.sdb.ItemAttribute;
import com.netflexitysolutions.amazonws.sdb.SimpleDB;
import com.netflexitysolutions.amazonws.sdb.Statistics;

/**
 * @author netflexity
 *
 */
public class GetAttributesOperation extends OperationExecutor<GetAttributes, Item>{
	
	private String domainName;
	private String id;
	private List<ItemAttribute> attributes;
	
	/**
	 * @param simpleDB
	 * @param domain
	 * @param item
	 */
	public GetAttributesOperation(SimpleDB simpleDB, Domain domain, Item item) {
		super(simpleDB);
		
		this.domainName = domain.getName();
		assert(StringUtils.isNotBlank(this.domainName));
		
		this.id = item.getIdentifier();
		assert(StringUtils.isNotBlank(this.id));
		
		this.attributes = item.getAttributes();
	}
	
	/* (non-Javadoc)
	 * @see com.netflexitysolutions.amazonws.sdb.internal.OperationExecutor#call(java.lang.Object)
	 */
	@Override
	protected Item call(GetAttributes request){
		Item foundItem = new Item();
		foundItem.setIdentifier(id);
		
		// Prepare request.
		request.setDomainName(domainName);
		request.setItemName(id);
		
		// See if we got any attribute names.
		if(attributes != null){
			for (ItemAttribute attr : attributes) {
				request.getAttributeName().add(attr.getName());
			}
		}
		
		// Invoke operation.
		GetAttributesResponse response = getSimpleDB().getService().getAttributes(request);
		if(response != null){
			ResponseMetadata metadata = response.getResponseMetadata();
			if(metadata != null){
				this.stats = new Statistics(metadata.getRequestId(), metadata.getBoxUsage());
			}
			GetAttributesResult result = response.getGetAttributesResult();
			if(result != null){
				List<Attribute> attributes = result.getAttribute();
				for (Attribute attribute : attributes) {
					foundItem.addAttribute(attribute.getName(), attribute.getValue(), true);
				}
				this.stats.setRecordCount(attributes.size());
			}
		}
		return foundItem;
	}
}
